#=
估算
=#


"""
mc积分
"""
function rich_simpling(S, O; xmin=-10, xmax=10)
    sct = 100000
    sps = (xmax-xmin)*rand(sct) .+ xmin
    num = 0.0
    den = 0.0
    eS = exp(-S)
    eSO = eS*O
    println("$eS $eSO")
    vars = Symbolics.get_variables(S)
    @assert length(vars) == 1
    for v in sps
        num += Symbolics.value(Symbolics.substitute(eSO, Dict(vars[1]=>v)))
        #num += substitute(eSO, Dict(vars[1]=>v))
        #println(v, num)
        den += Symbolics.value(Symbolics.substitute(eS, Dict(vars[1]=>v)))
        #den += substitute(eS, Dict(vars[1]=>v))
        #println(v, den)
    end
    return num/den
end


"""
langvein动力学
"""
function langvein_step(t::Int, xval::Float64, S, O)
    dt = 0.01
    xt = xval
    vars = Symbolics.get_variables(S)
    @assert length(vars) == 1
    #x(t+dt) - x(t) / dt = -∂S/∂x + ωdt
    ∂S_∂x = Symbolics.derivative(S, vars[1])
    ∂S_∂xval = Symbolics.value(Symbolics.substitute(∂S_∂x, Dict(vars[1]=>xval)))
    #∂S_∂xval = substitute(∂S_∂x, Dict(vars[1]=>xval))
    #println("$xval $∂S_∂xval ->")
    xnew = xt - 0.5*dt*∂S_∂xval + sqrt(dt)*rand(Normal(0, 1.0))
    #println(xnew)
    return t+1, xnew, Symbolics.fixpoint_sub(O, Dict(vars[1]=>xval))
end


"""
langvein动力学
"""
function complex_langvein_step(t::Int, xval::ComplexF64, S, O)
    dt = 0.01
    xt = xval
    vars = Symbolics.get_variables(S)
    @assert length(vars) == 1
    #x(t+dt) - x(t) / dt = -∂S/∂x + ωdt
    ∂S_∂x = Symbolics.derivative(S, vars[1])
    ∂S_∂xval = Symbolics.value(Symbolics.substitute(∂S_∂x, Dict(vars[1]=>xval)))
    @assert isapprox(∂S_∂xval, 2xval)
    xr = real(xt)# xt - 0.5*dt*∂S_∂xval + sqrt(dt)*randn()
    xi = imag(xt)
    xrnew = xr - 0.5*dt*real(∂S_∂xval) + sqrt(dt)*rand(Normal(0, 1.0))
    #有些用Normal(0, sqrt(2.0))是因为用了dt = 2ϵ
    #xrnew = xr - 2dt*xr + sqrt(dt)*rand(Normal(0, sqrt(2.0)))
    xinew = xi - 0.5*dt*imag(∂S_∂xval)# + sqrt(dt)*rand(Normal(0, sqrt(1.0))))
    return t+1, complex(xrnew, xinew), Symbolics.value(Symbolics.substitute(O, Dict(vars[1]=>xval)))
end
